package 算法.NiuKe.JZ;

import java.util.ArrayList;

/**
 * @author:谢君臣
 * @Date:2021/3/2110:24
 * @version:1.0
 * @function: 输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字。
 */
public class JZ19 {
    public static void main(String[] args) {

    }

    public int[] spiralOrder(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
            return new int[0];
        int n = matrix.length, m = matrix[0].length;
        int[] res = new int[m * n];
        int index = 0;
        int top = 0, left = 0, right = m-1, bottom = n-1;
        while (top <= bottom && left <= right) {
            for (int columns = left; columns <= right; columns++) {
                res[index++] = matrix[top][columns];
            }
            for (int row = top+1; row <= bottom; row++) {
                res[index++] = matrix[row][right];
            }
            if (top < bottom && left < right) {
                for (int columns = right; columns > left; columns--) {
                    res[index++] = matrix[bottom][columns];
                }
                for (int row = bottom; row > top; row--) {
                    res[index++] = matrix[row][left];
                }
            }
            top++;
            left++;
            bottom--;
            right--;
        }
        return res;
    }
    public ArrayList<Integer> printMatrix(int [][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
            return null;
        int n = matrix.length, m = matrix[0].length;
        ArrayList<Integer> res = new ArrayList<>();
        int top = 0, left = 0, right = m, bottom = n;
        while (top <= bottom && left <= right) {
            for (int columns = left; columns <= right; columns++) {
                res.add(matrix[top][columns]);
            }
            for (int row = top+1; row <= bottom; row++) {
                res.add(matrix[row][right]);
            }
            if (top < bottom && left < right) {
                for (int columns = right - 1; columns > left; columns--) {
                    res.add(matrix[bottom][columns]);
                }
                for (int row = bottom; row > left; row--) {
                    res.add(matrix[row][left]);
                }
            }
            top++;
            left++;
            bottom--;
            right--;
        }
        return res;
    }
}
